# coding=utf-8
import logging
from common import orm
from common.card_statistics_weekly import handler as helper
from common.card_statistics_weekly.model import CardStatisticsWeekly
from common.order_withdraw.model import OrderWithdraw
from common.utils import exceptions as err
from common.utils import id_generator
from common.utils.db import list_object, get, upsert, list_export_object, generate_filter
from common.utils.decorator import sql_wrapper
from common.utils.types import Enum
from datetime import datetime, timedelta, date
from decimal import Decimal
from sqlalchemy import func, Date, cast

_LOGGER = logging.getLogger('hydra')


@sql_wrapper
def get_cards_statistics(card_code):
    weekly = CardStatisticsWeekly.query.filter(CardStatisticsWeekly.card_code == card_code,
                                               cast(CardStatisticsWeekly.created_at, Date) == date.today()).first()
    if not weekly:
        weekly = CardStatisticsWeekly()

    return weekly


@sql_wrapper
def upsert_card_statistics(card_code, order_amount, order_status=-1, reverse=False):
    days_of_week = helper.get_day_of_week()
    weekly = {}
    for x in days_of_week:
        weekly = CardStatisticsWeekly.query.filter(CardStatisticsWeekly.card_code == card_code,
                                                   cast(CardStatisticsWeekly.created_at, Date) == x).first()
        if weekly:
            break

    if order_status == -1:
        if not weekly:
            weekly = CardStatisticsWeekly()
            weekly.created_at = datetime.utcnow()
            weekly.card_code = card_code

        amount = Decimal(order_amount if not reverse else -order_amount)
        count = 1 if not reverse else 1
        weekly.total_amount += amount
        weekly.payment_amount += amount
        weekly.processing_amount += amount
        weekly.total_count += count
        weekly.payment_count += count
        weekly.processing_count += count
        weekly.updated_at = datetime.utcnow()
        weekly.save()
    else:
        if weekly:
            weekly.processing_amount -= order_amount;
            weekly.processing_count -= 1

            if order_status == 2:  # ORDER_STATUS.SUCCESS:
                weekly.auto_close_amount += order_amount;
                weekly.auto_close_count += 1
            elif order_status == 3:  # ORDER_STATUS.MANUALSUCCESS:
                weekly.manual_close_amount += order_amount
                weekly.manual_close_count += 1
            elif order_status == 4:  # ORDER_STATUS.INVALID:
                weekly.invalid_amount += order_amount
                weekly.invalid_count += 1
            weekly.updated_at = datetime.utcnow()
            weekly.save()
